package com.xc.pay.ali;

import com.alipay.api.*;
import com.xc.pay.ali.enums.AliMethodEnum;
import com.xc.pay.ali.util.VerifyPayParamUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 支付宝支付发送请求
 *
 * @author rongrong
 * @date 2020/11/24
 */
public class AliPayRequestUtil<
    R extends AlipayRequest, M extends AlipayObject, S extends AlipayResponse> {

  private static final Logger log = LoggerFactory.getLogger(AliPayRequestUtil.class);

  /** 支付类型枚举 */
  private final AliMethodEnum payType;

  public AliPayRequestUtil(AliMethodEnum payType) {
    this.payType = payType;
  }

  /**
   * 请求支付宝获取响应信息
   *
   * @param notifyUrl 回调地址
   * @param request 请求信息
   * @param model 参数信息
   * @return AlipayTradePrecreateResponse
   * @throws AlipayApiException 异常
   */
  protected S createPayRequest(AlipayClient alipayClient, String notifyUrl, R request, M model)
      throws AlipayApiException {
    // 验证参数
    log.info("验证参数...");
    VerifyPayParamUtil.verifyParam(model, payType);
    log.info("验证完毕-----");
    request.setBizModel(model);
    // 设置异步通知地址
    request.setNotifyUrl(notifyUrl);
    try {
      log.info("发送请求----->");
      if (AliMethodEnum.APP_PAY_METHOD == payType) {
        return (S) alipayClient.sdkExecute(request);
      } else if (AliMethodEnum.TRADE_WAP_PAY == payType
          || AliMethodEnum.TRADE_PAGE_PAY == payType) {
        return (S) alipayClient.pageExecute(request);
      } else {
        return (S) alipayClient.execute(request);
      }
    } catch (AlipayApiException e) {
      throw new AlipayApiException(e.getMessage());
    }
  }
}
